package com.itheima.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查找所有用户
     * @return
     */
    @GetMapping("/findAll")
    public List<User> findAll(){
        return userService.findAll();
    }

    /**
     * 增加缓存查询用户资源
     * @return
     */
    @GetMapping("/findAllCache")
    public String findAllCache() throws JsonProcessingException {
        String userStr="";
        //查询redis缓存
        userStr = (String)redisTemplate.boundValueOps("userAll364").get();
        //存在
        //不存在 去数据库查找 转为json字符串11放入redis中
        /*if (null !=userStr && "" !=userStr){

        }*/
        if (StringUtils.isEmpty(userStr)){
            log.info("------------从数据中查找");
            //不存在
            List<User> userList = userService.findAll();
            ObjectMapper mapper = new ObjectMapper();
            userStr=mapper.writeValueAsString(userList);
            redisTemplate.boundValueOps("userAll364").set(userStr);
            return userStr;
        }else {
            //存在
            return userStr;
        }
    }
}
